package com.module.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.module.framework.domain.Category;
import com.module.framework.domain.LoginUser;
import com.module.framework.domain.Staff;
import com.module.framework.domain.User;
import com.module.framework.mapper.StaffMapper;
import com.module.framework.mapper.UserMapper;
import com.module.framework.service.LoginService;
import com.module.framework.utils.BeanCopyUtils;
import com.module.framework.utils.JwtUtil;
import com.module.framework.utils.RedisCache;
import com.module.framework.vo.UserInfoVO;
import com.module.framework.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author JiHuiQin
 * @Date 2022/2/14 20:53
 * @Version 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StaffMapper staffMapper;

    @Override
    public UserLoginVO login(User user) {
        // 封装成Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 使用authenticationManager进行用户认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断认证是否通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        // 认证通过，使用userId生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        // 将用户信息存入redis，userId作为key
        redisCache.setCacheObject("login:" + userId, loginUser);

        // 返回给前端的数据
        UserInfoVO userInfoVO = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVO.class);
        UserLoginVO userLoginVO = new UserLoginVO(jwt, userInfoVO);
        return userLoginVO;
    }

    @Override
    public void logout() {
        // 获取当前登录用户的信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userId);
    }

    @Override
    public String register(User user) {
        String userName = user.getUserName();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(Objects.nonNull(userName), User::getUserName, userName);
        List<User> lists = userMapper.selectList(queryWrapper);
        if (lists.size() > 0) {
            return "此学号/工号此前已经注册过";
        }
//        List<Staff> staff = staffMapper.selectStaffInfoBySnCode(userName);
//        if (staff.size() > 0) {
            // 密码加密
            BCryptPasswordEncoder pa = new BCryptPasswordEncoder();
            String encode = pa.encode(user.getPassword());
            // 设置默认值
            user.setBan(0);
            user.setLendNumber(0);
            user.setNickName(user.getNickName());
            user.setRoleId(3L);
            user.setPassword(encode);
            userMapper.insert(user);
            return "注册成功";
//        } else {
//            return "学号/工号不在校内库中";
//        }
    }
}
